package com.ecnu.web.controller.tool;

import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.system.domain.SysEmail;
import com.ecnu.system.domain.dto.SmtpEmailDTO;
import com.ecnu.system.domain.dto.UpdatePwdDTO;
import com.ecnu.system.service.IEmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "邮箱验证")
@RestController
@RequestMapping("/email")
@Validated
public class EmailController {

    @Autowired
    private IEmailService emailService;

    @GetMapping("/send")
    @ApiOperation(value = "验证码验证")
    public void sendEmail(String email, String code) {
//        this.sendCode(email);

        // 模拟用户输入验证码
        String userInputCode = code; // 假设用户输入的验证码
        boolean isValid = emailService.verifyCode(email, userInputCode);

        if (isValid) {
            System.out.println("验证码验证成功！");
        } else {
            System.out.println("验证码验证失败！");
        }
    }

    @PostMapping("/updatepwd")
    @ApiOperation(value = "修改密码")
    public AjaxResult updatePwd(@Validated @RequestBody UpdatePwdDTO dto) {
        return emailService.updatePwd(dto);
    }

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @ApiOperation(value = "验证码发送")
    @GetMapping("/get")
    public AjaxResult getCode(@NotBlank(message = "邮箱不能为空")
                                  @Email(regexp = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$",
                                          message = "邮箱格式不正确")
                                  @Size(max = 254, message = "邮箱长度不能超过254个字符")
                                  String email
    ){
        try {

            return emailService.sendCode(email);
        }catch (Exception   w){
            return AjaxResult.error("验证码发送失败：" + w.getMessage());
        }
    }

    @GetMapping("/smtpCode")
    @ApiOperation(value = "获取邮箱配置")
    @PreAuthorize("@ss.hasPermi('email:smtpCode')")
    public AjaxResult smtpCode() {
        SysEmail sysEmail = emailService.smtpCode();
        return AjaxResult.success(sysEmail == null ? new SysEmail() : sysEmail);
    }

    @PostMapping("/smtpEdit")
    @PreAuthorize("@ss.hasPermi('email:smtpEdit')")
    @ApiOperation(value = "邮箱配置编辑")
    public AjaxResult smtpCodeEdit(@Valid @RequestBody SmtpEmailDTO dto) {
        return emailService.smtpCodeEdit(dto);
    }
}
